package com.hoshiicloud.user.service.impl.organization;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.utils.UidGenerate4C;
import com.hoshiicloud.user.entity.company.Settlement;
import com.hoshiicloud.user.entity.organization.StoreOrganization;
import com.hoshiicloud.user.entity.store.PlatStore;
import com.hoshiicloud.user.feign.IdGeneratorService;
import com.hoshiicloud.user.mapper.organization.StoreOrganizationMapper;
import com.hoshiicloud.user.service.company.ICompanyService;
import com.hoshiicloud.user.service.company.ISettlementService;
import com.hoshiicloud.user.service.organization.StoreOrganizationService;
import com.hoshiicloud.user.service.platform.PlatformService;
import com.hoshiicloud.user.service.store.PlatStoreService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 店铺（伙伴/供应商) 服务实现类
 * </p>
 *
 * @author campchen
 * @since 2019-04-28
 */
@Slf4j
@Service
public class StoreOrganizationServiceImpl extends ServiceImpl<StoreOrganizationMapper, StoreOrganization> implements StoreOrganizationService {

    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private PlatformService platformService;
    @Autowired
    private PlatStoreService storeService;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private ISettlementService settlementService;

    /**
     * @return IPage
     * @description: 分页查询店铺（伙伴/供应商)
     */
    @Override
    @Logable(authName = "供应商信息-店铺（伙伴/供应商)管理-分页查询店铺（伙伴/供应商)")
    @Cacheable(cacheNames = "StoreOrganization", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public IPage<StoreOrganization> getPage(IPage page, QueryWrapper queryWrapper, String key) {
        return baseMapper.selectPage(page, queryWrapper);
    }

    /**
     * @param id
     * @return com.hoshiicloud.organization.entity.StoreOrganization
     * @description: 根据id查询店铺（伙伴/供应商)
     */
    @Override
    @Cacheable(cacheNames = "StoreOrganization", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "供应商信息-店铺（伙伴/供应商) -查询店铺（伙伴/供应商) ")
    public StoreOrganization getById(Long id) {
        return baseMapper.selectById(id);
    }


    /**
     * @Author:campchen
     * @Description:
     * @Date:下午 06:45 2019/5/11
     * @Param:
     * @return:
     */
    @Cacheable(cacheNames = "StoreOrganization", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#orgcode")
    @Logable(authName = "供应商信息-机构表 -查询机构表 ")
    @Override
    public StoreOrganization getByOrgcode(String orgcode) {
        Wrapper<StoreOrganization> wrapper = Wrappers.<StoreOrganization>query().lambda().eq(StoreOrganization::getOrgCode, orgcode);
        return baseMapper.selectOne(wrapper);
    }

    /**
     * @return boolean
     * @description: 新增店铺（伙伴/供应商)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "StoreOrganization", allEntries = true)
    @Logable(authName = "供应商信息-店铺（伙伴/供应商)-新增店铺（伙伴/供应商)")
    public String insert(StoreOrganization entity) {
        String id = idGeneratorService.queryGeneratorId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        Settlement settlement = settlementService.getById(entity.getPaymentId());
        if (null == settlement) {
            throw new ServiceException("新增失败,结算方式信息有误");
        }
        PlatStore platStore = storeService.getById(entity.getStoreId());
        if (null == platStore) {
            throw new ServiceException("新增失败,店铺信息有误");
        }
        //判断编码是否可用
        String orgcode = null;
        Boolean flag = true;
        int num = 1;
        //生成7位编码
        UidGenerate4C idWorker = new UidGenerate4C(num);
        while (flag) {
            num++;
            orgcode = "5" + "3" + String.valueOf(idWorker.getNextId()).substring(10, 17);
            StoreOrganization comOrganizationOrgCode = getByOrgcode(orgcode);
            if (comOrganizationOrgCode == null || "".equals(comOrganizationOrgCode)) {
                flag = false;
            }
        }
        entity.setOrgCode(orgcode);
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return id;
    }

    /**
     * @return boolean
     * @description: 修改店铺（伙伴/供应商)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "StoreOrganization", allEntries = true)
    @Logable(authName = "供应商信息-店铺（伙伴/供应商)管理-修改店铺（伙伴/供应商)")
    public boolean updateById(StoreOrganization entity) {
        /**如果供应商资料已修改需重新审核供应商资料*/
        if (entity.getStatus() == null || "".equals(entity.getStatus())) {
            entity.setStatus(0);
        }
        entity.setModifiedTime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }

    @Override
    public boolean updateById(Long id, Integer status) {
        if (status != 0 && status != 1 && status != 2) {
            throw new ServiceException(CommonError.error("审核状态错误"));
        }
        StoreOrganization storeOrganization = new StoreOrganization();
        storeOrganization.setId(id);
        storeOrganization.setStatus(status);
        storeOrganization.setModifiedTime(LocalDateTime.now());
        int row = baseMapper.updateById(storeOrganization);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }

    @Override
    @Cacheable(cacheNames = "StoreOrganization", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "供应商信息-店铺（伙伴/供应商) -查询店铺（伙伴/供应商) ")
    public List<StoreOrganization> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }

}
